<script setup lang="ts">
import type { UploadFile } from 'element-plus'
import type { ResWrapper } from '@/apis/common/commonApi'
import { UploadFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { storeToRefs } from 'pinia'
import { computed, onMounted, ref } from 'vue'
import { useDictStore } from '@/stores/dictStore'
import { useLoginStore } from '@/stores/loginStore'

const emits = defineEmits(['onUploadSuccess'])

const dialogVisible = ref(false)
const fileGroup = ref<string>()
const loginStore = useLoginStore()

const uploadInfo = computed(() => {
  return {
    action: `${import.meta.env.VITE_API_BASE_URL}/system/file/upload/${fileGroup.value}`,
    headers: { 'Authorization': `Bearer ${loginStore.user.token}`, 'app-type': 'MANAGE', 'app-ver': import.meta.env.VITE_APP_VERSION },
  }
})
const show = () => dialogVisible.value = true
const hide = () => dialogVisible.value = false

function onUploadSuccess(response: ResWrapper<any>, uploadFile: UploadFile) {
  if (!response.success) {
    ElMessage.error(`${response.errCode}-${response.errMsg}`)
    uploadFile.status = 'fail'
  }
  else {
    hide()
    ElMessage.success('上传成功')
    emits('onUploadSuccess')
  }
}

const dictStore = useDictStore()
const { dictMap } = storeToRefs(dictStore)

onMounted(async () => {
  await dictStore.loadDict('FILE_GROUP')
  if (dictMap.value.FILE_GROUP && dictMap.value.FILE_GROUP.length > 0) {
    fileGroup.value = dictMap.value.FILE_GROUP[0].dictCode
  }
})

defineExpose({
  show,
  hide,
})
</script>

<template>
  <el-dialog v-model="dialogVisible" title="上传文件" width="500" destroy-on-close>
    <el-select
      v-model="fileGroup" value-key="groupName"
      placeholder="请选择文件分组"
    >
      <el-option
        v-for="item in dictMap.FILE_GROUP"
        :key="item.dictCode"
        :label="item.dictName"
        :value="item.dictCode!"
      />
    </el-select>
    <el-upload
      class="mt-2"
      drag
      :action="uploadInfo.action"
      :on-success="onUploadSuccess"
      :headers="uploadInfo.headers"
      :show-file-list="false"
      crossorigin="use-credentials"
    >
      <el-icon class="el-icon--upload">
        <UploadFilled />
      </el-icon>
      <div class="el-upload__text">
        拖动文件到这里或者<em>点击上传</em>
      </div>
    </el-upload>
  </el-dialog>
</template>
